package cn.tedu.basic;


//测试实现接口Runnable 售票案例
public class Test2_Thread {
    public static void main(String[] args) {

        Tickets1 target =new Tickets1();
        Thread t =new Thread(target);
        Thread t1 =new Thread(target);
        Thread t2 =new Thread(target);
        Thread t3 =new Thread(target);
        t.start();
        t1.start();
        t2.start();
        t3.start();
        tickets2 target1 =new tickets2();
        Thread t4 =new Thread(target1);
        Thread t5 =new Thread(target1);
        t4.start();
        t5.start();

    }
}
 class Tickets1 implements Runnable{
        int sum =100;
    @Override
  synchronized public void run() {//加同步锁关键字
       while (true){
           if (sum>0){
               try {
                   Thread.sleep(100);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               System.out.println(Thread.currentThread().getName()+"--"+sum--);
           }else {
               break;
           }
       }
    }
}
class tickets2 implements Runnable{
    int sum =100;
    Object o =new Object();
    @Override
    public void run() {
        while (true){
            synchronized (o) {//同步代码块的锁对象，可以任意，但必须是同一个对象；
                if (sum > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "-=-" + sum--);
                } else {
                    break;
                }
            }
        }
    }
}
class MeiNv implements Runnable{
    int sum =100;
    @Override
   synchronized public void run() {
        while (true){
            if (sum>0){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"=="+sum--);
            }else{
                break;
            }
        }
    }
}
class KongJie1 implements Runnable{
    int sum =100;
    @Override
    public void run() {
        while (true){
            synchronized (this) {
                if (sum > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "==" + sum--);
                } else {
                    break;
                }
            }
        }
    }
}